﻿using SmartWMS.Common.Extensions;
using SmartWMS.Common.ResponseOutput;
using SmartWMS.Domain.Base;
using SmartWMS.Domain.BasicsDatum;
using SmartWMS.Domain.BusinessManage;
using SmartWMS.Domain.WarehouseManage;
using SmartWMS.Server.BusinessServer.SalesReturns.Dto;
using SmartWMS.Server.Repository;
using SmartWMS.Server.WarehouseManage.LossReportingServices.Dto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartWMS.Server.WarehouseManage.LossReportingServices
{
    /// <summary>
    /// 报损管理实现层
    /// </summary>
    public class LossReportingServices : ILossReportingServices
    {
        /// <summary>
        /// 构造函数(报损表)
        /// </summary>
        private readonly IRepository<FrmLoss> _frmloss;

        /// <summary>
        /// 构造函数(报损明细表)
        /// </summary>
        private readonly IRepository<FrmLossDetail> _frmlossDetail;

        /// <summary>
        /// 构造函数(产品表)
        /// </summary>
        private readonly IRepository<Product> _product;

        /// <summary>
        /// 构造函数(入库表)
        /// </summary>
        private readonly IRepository<InWarehouse> _inwarehouse;

        /// <summary>
        /// 构造函数(仓库)
        /// </summary>
        private readonly IRepository<Warehouse> _warehouses;

        /// <summary>
        /// 构造函数(库位)
        /// </summary>
        private readonly IRepository<Location> _locations;

        /// <summary>
        /// 构造函数(入库明细表)
        /// </summary>
        private readonly IRepository<InWarehouseDetail> _inwarehouseDetail;
        /// <summary>
        /// 构造函数(销售明细)
        /// </summary>

        private readonly IRepository<SalesManageDetail> _SalesManageDetail;
        /// <summary>
        /// 构造函数(销售明细)
        /// </summary>

        private readonly IRepository<SalesManagement> _SalesManagement;

        /// <summary>
        /// 构造函数(类别)
        /// </summary>
        private readonly IRepository<Category> _category;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="frmloss">报损表</param>
        /// <param name="frmlossDetail">报损明细表</param>
        /// <param name="product">产品表</param>
        /// <param name="inwarehouse">入库表</param>
        /// <param name="inwarehouseDetail">入库明细表</param>
        /// <param name="warehouses">仓库表</param>
        /// <param name="locations">库位表</param>
        public LossReportingServices(IRepository<FrmLoss> frmloss, IRepository<FrmLossDetail> frmlossDetail, IRepository<Product> product, IRepository<InWarehouse> inwarehouse, IRepository<InWarehouseDetail> inwarehouseDetail, IRepository<Warehouse> warehouses, IRepository<Location> locations, IRepository<Category> category, IRepository<SalesManageDetail> salesManageDetail, IRepository<SalesManagement> salesManagement)
        {
            _frmloss = frmloss;
            _frmlossDetail = frmlossDetail;
            _product = product;
            _inwarehouse = inwarehouse;
            _inwarehouseDetail = inwarehouseDetail;
            _warehouses = warehouses;
            _locations = locations;
            _category = category;
            _SalesManageDetail = salesManageDetail;
            _SalesManagement = salesManagement;
        }

        /// <summary>
        /// 添加报损信息
        /// </summary>
        /// <returns></returns>
        public Task<Response<bool>> AddFrmlossAsync(LossDto dto)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 报损列表显示
        /// </summary>
        /// <returns></returns>
        public async Task<Response<dynamic>> ShowFrmlossAsync(whereDto dto)
        {
            var products = await _product.GetAllListAsync();//产品
            var frmlosss = await _frmloss.GetAllListAsync();//报损
            var frmlossDetail = await _frmlossDetail.GetAllListAsync();//报损明细
            var locations = await _locations.GetAllListAsync();//库位
            var inwareDetail = await _inwarehouseDetail.GetAllListAsync();//入库明细
            var warehouses = await _warehouses.GetAllListAsync();//仓库
            var list = (from a in products
                        join b in frmlossDetail on a.ProductCode equals b.ProductCode
                        join c in frmlosss on b.FrmLossCode equals c.FrmLossCode
                        join d in inwareDetail on a.ProductCode equals d.ProductCode
                        join e in locations on a.DefaultWarehouseId equals e.Id
                        join f in warehouses on a.DefaultLocationId equals f.Id
                        select new LossDto
                        {
                            Id = b.Id,
                            FrmLossCode = c.FrmLossCode,
                            ProductCode = a.ProductCode,
                            ProductName = a.ProductName,
                            Batch = d.Batch,
                            Unit = a.Unit,
                            Creator = c.Creator,
                            CreatorTime = c.CreatorTime,
                            InWarehouseNumber = d.InWarehouseNumber,
                            Name = f.Name,
                            LocationName = e.LocationName,
                            FrmLossType = c.FrmLossType,
                            State = c.State,
                            Reviewer = c.Reviewer,
                            Audittime = c.Audittime,
                        }).Distinct().ToList();
            if (!string.IsNullOrEmpty(dto.FrmLossCode))
            {
                list = list.Where(x => x.FrmLossCode.Contains(dto.FrmLossCode)).ToList();
            }
            if (dto.FrmLossType != null)
            {
                list = list.Where(x => x.FrmLossType == dto.FrmLossType).ToList();
            }
            if (dto.State != 0)
            {
                list = list.Where(x => x.State == dto.State).ToList();
            }

            //分页
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / dto.PageSize);
            list = list.Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToList();
            var result = list.MapToList<LossDto>();
            return Response<dynamic>.Ok(new
            {
                totalCount,
                pageCount,
                result
            });
        }

        /// <summary>
        /// 删除报损信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<bool>> DeleteFrmlossAsync(KeyEntity id)
        {
            var resault = id.MapTo<FrmLoss>();
            var deletelist = await _frmloss.DeleteByIdAsync(resault);
            return deletelist > 0 ? Response<bool>.Ok(true) : Response<bool>.Fail(false);
        }

        /// <summary>
        /// 批量删除报损信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<bool>> BatchDelFrmlossAsync(string id)
        {
            var ids = id.Split(',');
            var list = new List<FrmLoss>();
            foreach (var item in ids)
            {
                var pList = _frmloss.GetListQuery().Where(t => t.Id == int.Parse(item));
                list.AddRange(pList);
            }
            var result = await _frmloss.DeleteAsync(list);
            return result > 0 ? Response<bool>.Ok(result > 0) :
                 Response<bool>.Fail(result > 0);
        }

        /// <summary>
        /// 产品列表显示
        /// </summary>
        /// <returns></returns>
        public async Task<Response<dynamic>> ShowProductAsync(ProductsDto dto)
        {
            var prods = await _product.GetAllListAsync();
            var cates = await _category.GetAllListAsync();
            var sale = await _SalesManageDetail.GetAllListAsync();
            var sales = await _SalesManagement.GetAllListAsync();

            var list = (from a in prods
                        join b in cates on a.ProductTypeId equals b.Id
                        select new ProductsDto
                        {
                            Id = a.Id,
                            Inventory = a.Inventory,
                            ProductCode = a.ProductCode,
                            ProductName = a.ProductName,
                            CategoryName = b.CategoryName,
                            Remarks = b.Remarks,
                            Specs = a.Specs,
                            Unit = a.Unit,
                            Price = a.Price,
                            Weight = a.Weight,
                            PackageType = a.PackageType,
                            ProductId = a.Id,
                        }).Distinct().ToList();
            if (!string.IsNullOrEmpty(dto.ProductCode))
            {
                list = list.Where(x => x.ProductCode.Contains(dto.ProductCode)).ToList();
            }
            if (!string.IsNullOrEmpty(dto.ProductName))
            {
                list = list.Where(x => x.ProductName.Contains(dto.ProductName)).ToList();
            }
            //分页
            int totalCount = list.Count();
            int pageCount = (int)Math.Ceiling(totalCount * 1.0 / dto.PageSize);
            list = list.Skip((dto.PageIndex - 1) * dto.PageSize).Take(dto.PageSize).ToList();
            var result = list.MapToList<ProductsDto>();
            return Response<dynamic>.Ok(new
            {
                totalCount,
                pageCount,
                result
            });
        }

        /// <summary>
        /// 查看报损信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Response<detailDto>> ReverseFrmlossAsync(detailDto dto)
        {
            var frml = _frmloss.GetAllListAsync().Result.FirstOrDefault(x => x.FrmLossCode == dto.FrmLossCode);
            var frmldetail = _frmlossDetail.GetAllListAsync().Result.Where(x => x.FrmLossCode == dto.FrmLossCode).ToList();
            var prod = await _product.GetAllListAsync();
            var loca = await _locations.GetAllListAsync();
            var frmls = new detailDto
            {
                FrmLossCode = frml.FrmLossCode,
                FrmLossType = frml.FrmLossType,
                State = frml.State,
                Creator = frml.Creator,
                CreatorTime = frml.CreatorTime,
                Remarks = frml.Remarks,
                Opinion = frml.Opinion,
                ListProduct = frmldetail.Select(x => new listDto
                {
                    FrmLossCode = dto.FrmLossCode,
                    ProductCode = x.ProductCode,
                    ProductName = prod.FirstOrDefault(x => x.ProductCode == x.ProductCode).ProductName,
                    Unit = prod.FirstOrDefault(x => x.ProductCode == x.ProductCode).Unit,
                    FrmLossNum = x.FrmLossNum,
                    LocationName = loca.FirstOrDefault(x => x.Id == x.Id).LocationName,
                }).ToList(),
            };
            return Response<detailDto>.Ok(frmls);
        }
    }
}
